const fs = require('fs')
// const request = require('request')
const axios = require('axios').default;

function sleep(timeout = 0) {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve();
        }, timeout);
    })
}

// 判断存在
function fileExists(file) {
    return new Promise((resolve, reject) => {
        fs.access(file, err => {
            if (err) {
                if (err.code === 'ENOENT') {
                    resolve(false)
                } else {
                    reject(err)
                }
            } else {
                resolve(true)
            }
        })
    })
}

// function readRemoteFile(url) {
//     return new Promise((resolve,reject) => {
//         request.get(url, function (error, response, body) {
//             if (!error && response.statusCode == 200) {
//                 resolve(body)
//             } else {
//                 resolve()
//             }
//         });
//     })
// }

function readRemoteFile(url) {
    return new Promise((resolve, reject) => {
        axios({
            method: 'get',
            url: encodeURI(url)
        })
            .then(function (response) {
                // console.log(response);
                if (response.status === 200) {

                    resolve(response.data);
                } else {
                    reject(new Error(`Request Failed,Status Code: ${response.status}`))
                    // logger.error('doRequest error: ', `Request Failed,Status Code: ${response.status}`)
                }
            })
            .catch(function (error) {
                //   logger.error('download error: ', error.message)
                reject(error);
            });

    })
}


function padNumber(num, n) {
    var len = num.toString().length;
    while(len < n) {
      num = "0" + num;
      len++;
    }
    return num;
  }



module.exports = {
    sleep,
    fileExists,
    readRemoteFile,
    padNumber
}